package org.nowcoder.leetcode.string;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 * Title  : 451. Sort Characters By Frequency
 * Source : https://leetcode.cn/problems/sort-characters-by-frequency/description/
 * Author : XrazYang
 * Date   : 2023-10-20
 */

public class LeetCode_451 {
    public String frequencySort(String s) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int k = map.getOrDefault(c, 0);
            map.put(c, k + 1);
        }
        final StringBuilder builder = new StringBuilder();
        map.entrySet().stream()
                .map(entry -> String.valueOf(entry.getKey()).repeat(entry.getValue()))
                .sorted(Comparator.comparingInt(String::length).reversed())
                .forEach(builder::append);
        return builder.toString();
    }
}
